<?php
/**
 * Created by PhpStorm.
 * User: yandian
 * Date: 2017/4/25
 * Time: 20:01
 */

namespace app\weixin\controller;


use app\common\controller\LiteBase;
use app\common\model\MemberLuck;
use app\common\model\Prize;
use app\common\util\DateTimeUtil;
use app\common\util\LoginManager;

/**
 * 爱心抽奖
 * Class Luck
 * @package app\weixin\controller
 */
class Luck extends LiteBase
{
    public function index()
    {
        $mid = LoginManager::getLoginUserId();
        $prizes = Prize::instance()
            ->join('member m', 'm.id=prize.member_id')
            ->field('prize.*,m.nickname,m.avatar')
            ->order('id desc')->limit(0, 50)->select();
        $this->assign('prizes', $prizes);
        $myprizes = Prize::instance()->where(['member_id' => $mid])->select();
        $this->assign('myprizes', $myprizes);
        return $this->fetch();
    }

    public function index2()
    {
        die;
        $prizes = Prize::instance()
            ->join('luck', 'luck.id=prize.luck_id')
            ->join('member m', 'm.id=prize.member_id')
            ->field('prize.*,m.nickname,m.avatar,luck.prize prize_name,luck.prize_img')
            ->order('id desc')->limit(0, 50)->select();

        //中奖商品列表
        $lucks = \app\common\model\Luck::instance()->order('rate asc')->select();

        $results = [];
        //计算中奖概率
        $idx = 0;
        $perRan = intval(360 / (count($lucks) * 2 + 1));
        foreach ($lucks as $k => $v) {
            $results[] = [
                'level' => '谢谢参与',
                'rate' => -1,
                'ran' => $idx * $perRan,
                'id' => 0
            ];
            $idx++;
            $v['ran'] = $idx * $perRan;
            $results[] = $v;
        }
        $results[] = [
            'level' => '谢谢参与',
            'rate' => -1,
            'ran' => $idx * $perRan,
            'id' => 0
        ];
        $this->assign('prizes', $prizes);
        $this->assign('lucks', $results);
        $this->assign('goods', $lucks);
        return $this->fetch();
    }

    public function getMyPrize()
    {
        return $this->returnJson(\app\common\model\Prize::instance()
            ->join('luck', 'luck.id=prize.luck_id')
            ->where(['prize.member_id' => 0])
            ->order('prize.id desc')
            ->select());
    }

    public function startGame()
    {
        $instance = MemberLuck::instance();
        $mid = LoginManager::getLoginUserId();
        $luckRow = $instance->where(['member_id' => $mid, 'status' => 0])->order('id asc')->find();
        if (empty($luckRow)) {
            return $this->jsonFail('Sorry,您没有抽奖机会了');
        }
        $totalRate = ($luckRow['gift_rate'] + $luckRow['coral_rate']) / 100;

        if ($totalRate < 1) {
            $totalRate = 1;
        }

        $randFloat = function ($min = 0, $max = 1) {
            return $min + mt_rand() / mt_getrandmax() * ($max - $min);
        };

        $randNum = $randFloat(0, $totalRate);
        $info = 0;
        if ($luckRow['coral_rate'] > 0 && $randNum <= $luckRow['coral_rate']/100) { // 抽中珊瑚命名权
            $now = DateTimeUtil::now();
            Prize::instance()->add([
                'member_id' => $mid,
                'num' => 1,
                'status' => 1,
                'prize_type' => 1,
                'luck_id' => $luckRow['id'],
                'luck_time' => $now,
                'send_time' => $now
            ]);

            $coral = \app\common\model\Coral::instance();
            $coral->add([
                'member_id' => $mid,
                'title' => '',
                'donation_id' => $luckRow['donation_id'],
                'create_time' => DateTimeUtil::now(),
                'coral_no' => ($coral->where(['member_id' => $mid])->max('coral_no') ?: 0) + 1
            ]);
            $info = 1;
        } else {
            $totalRate -= $luckRow['coral_rate'];
            $randNum = $randFloat(0, $totalRate);
            if ($luckRow['gift_rate'] > 0 && $randNum <= $luckRow['gift_rate']/100) { // 抽中小礼物
                Prize::instance()->add([
                    'member_id' => $mid,
                    'num' => 1,
                    'status' => 0,
                    'prize_type' => 2,
                    'luck_id' => $luckRow['id'],
                    'luck_time' => DateTimeUtil::now()
                ]);
                $info = 2;
            }
        }
        $instance->where(['id' => $luckRow['id']])->setField('status', 1);
        $data['info'] = $info;
        if (empty($info)) { // 没有中奖
            $arr = array(0, 45 * 2, 45 * 4, 45 * 6);
            $data['ran'] = $arr[intval(rand(0, 3))];
        } elseif ($info == 1) { // 珊瑚
            $arr = array(45, 45 * 5);
            $data['ran'] = $arr[intval(rand(0, 1))];
        } elseif ($info == 2) { // 小礼物
            $arr = array(45 * 3, 45 * 7);
            $data['ran'] = $arr[intval(rand(0, 1))];
        }
        $data['time'] = DateTimeUtil::now();
        return $this->jsonSuccess($data);
    }


    public function startGame2()
    {
        $data = [];//存数据
        $rows = \app\common\model\Luck::instance()->order('rate asc')->select();
        $totalRate = 0;
        foreach ($rows as $row) {
            $totalRate += $row['rate'];
        }
        if ($totalRate < 1) {
            $totalRate = 1;
        }

        $randFloat = function ($min = 0, $max = 1) {
            return $min + mt_rand() / mt_getrandmax() * ($max - $min);
        };

        $result = [];
        $idx = 0;
        foreach ($rows as $k => $row) {
            $randNum = $randFloat(0, $totalRate);
            if ($row['rate'] > 0 && $randNum <= $row['rate']) {
                $result = $row;
                $idx = $k;
                break;
            }
            $totalRate -= $row['rate'];
        }

        $data['onceran'] = 40;
        $data['num'] = 1;

        if (empty($result)) { // 没有中奖
            $data['is_prize'] = 0;
            $data['status'] = 1;
            $arr = array(0, 80, 160, 240, 320);
            $data['ran'] = $arr[intval(rand(0, 3))];
            $data['actionStatus'] = 3;
            $data['prize'] = '没有中奖!';
            exit(json_encode($data));
        }

        $data['actionStatus'] = 1;
        $data['status'] = 1;
        $data['ran'] = 80 * (3 - $idx) + 40;
        $data['is_prize'] = 1;
        $data['prize'] = $result['level'];

        Prize::instance()->add([
            'member_id' => 0,
            'num' => 1,
            'status' => 0,
            'luck_id' => $result['id'],
            'luck_time' => DateTimeUtil::now(),
        ]);

        exit(json_encode($data));
    }
}